import '../util/_base_export.dart';
import '../util/_view_export.dart';

class SalesBloc extends LoadingMoreBase<Map> with ChangeNotifier {
  int pageindex = 1;
  bool _hasMore = true;
  bool forceRefresh = false;
  @override
  bool get hasMore =>
      (_hasMore && length < AppConst.prodQueryMax) || forceRefresh;

  Map<String, dynamic> criteria = {
    "category_id": "",
  };

  @override
  Future<bool> refresh([bool clearBeforeRequest = false]) async {
    _hasMore = true;
    pageindex = 1;
    //force to refresh list when you don't want clear list before request
    //for the case, if your list already has 20 items.
    forceRefresh = !clearBeforeRequest;
    var result = await super.refresh(clearBeforeRequest);
    forceRefresh = false;
    return result;
  }

  @override
  Future<bool> loadData([bool isloadMoreAction = false]) async {
    bool isSuccess = false;
    try {
      // //to show loading more clearly, in your app,remove this
      // await Future.delayed(Duration(milliseconds: 500));
      Map<String, dynamic> lm_param = criteria;
      lm_param.addAll({
        "offset": (pageindex - 1) * AppConst.prodQueryPagesize,
        "limit": AppConst.prodQueryPagesize,
        "wh_id": AppSession.wholesale_wh_id != 0
            ? AppSession.wholesale_wh_id
            : AppSession.wh_id
      });

      var lm_result = await AppSession.appReq.futureWrapper(
        ApiConst.httpPost,
        ApiServer.prod + ApiUri.query_sale_prods,
        {},
        lm_param,
        false,
        false,
      );
      var source = [];

      if ((lm_result ?? []).isNotEmpty) if (lm_result['ev_error'] == 0) {
        source = lm_result['ev_result']['prods'];

        // print(_sub_cate);
        notifyListeners();
      }
      if (pageindex == 1) {
        this.clear();
      }
      for (var item in source) {
        if (!this.contains(item) && hasMore) this.add(item);
      }

      _hasMore = source.length != 0;
      pageindex++;
      isSuccess = true;
    } catch (exception, stack) {
      isSuccess = false;
      print(exception);
      print(stack);
    }
    return isSuccess;
  }
}
